//
//  LLOauthViewController.swift
//  xinlangweibo
//
//  Created by 任玉林 on 16/6/25.
//  Copyright © 2016年 任玉林. All rights reserved.
//

import UIKit

import SVProgressHUD

import AFNetworking

class LLOauthViewController: UIViewController {
    
    override func loadView() {
        
        view = webView
        
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setupUI()
    }
    
    //设置视图
    private func setupUI(){
        
//        view.backgroundColor = UIColor.whiteColor()
        
        setNavc()
        
        
    }
    
    //懒加载 webview 视图
    private lazy var webView: UIWebView = {
        
        let view = UIWebView()
        
        view.delegate = self
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!

        let request = NSURLRequest(URL: url)
        
        view.loadRequest(request)
        
       return view
    }()
    
    //设置导航控制器
   private func setNavc(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain
            , target: self, action: "autoFillClick")
        
        navigationItem.title = "aout登录"
    }
    
    //取消按钮
    @objc private func cancelClick(){
        
        dismissViewControllerAnimated(true, completion: nil )
    }
    
    //自动填充按钮
    @objc private func autoFillClick(){
        
        let jsStr = "document.getElementById('userId').value='13623520325',document.getElementById('passwd').value='siage525525'"
        
        //注入js
        webView.stringByEvaluatingJavaScriptFromString(jsStr)

    }

}


//webView 代理方法
extension LLOauthViewController:UIWebViewDelegate{
    
    //网页开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    //网页加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //网页加载出错
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.URL?.absoluteString
        
        //判断url是否有值，并且 他的前缀是回调页
        if let u = urlStr where  u.hasPrefix(REDIRECT_URI) {
            
            //请求参数键值对
            let query = request.URL?.query
            
            //可选值判断
            if let q = query {
                
                let code = q.substringFromIndex("code=".endIndex)
                
                loadUserAccount(code)

            }
            
        }
        
        return true
    }
}

extension LLOauthViewController {
    
//    client_id	true	string	申请应用时分配的AppKey。
//    client_secret	true	string	申请应用时分配的AppSecret。
//    grant_type	true	string	请求的类型，填写authorization_code
//    
//    grant_type为authorization_code时
//    必选	类型及范围	说明
//    code	true	string	调用authorize获得的code值。
//    redirect_uri
    
    //获取token
    func loadUserAccount(code:String){
        
        LLNetwordTools.sharedtools.oauthLoadUserAccont(code, success: { (response) -> () in
            
            guard let res = response as? [String: AnyObject]
                else{
                    
                    return
                    
            }
            
            //字典转模型
            let userAccount = LLUserAccount(dict: res)
            
            self.loadUserInfo(userAccount)
            
            }) { (error) -> () in
                
                print(error)
        }
        
    }
    
    
    //获取个人信息
    func loadUserInfo(userAccount:LLUserAccount){
        
        LLNetwordTools.sharedtools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            
            guard let res = response as? [String: AnyObject]
                else{
                    
                    return
            }
//            print(res)
            
            //赋值
            userAccount.avatar_large = res["avatar_large"] as? String
            
            userAccount.screen_name = res["screen_name"] as? String
            
            //归档
            LLUserAccountTools.sharedTools.saveUserAccount(userAccount)
            //销毁百度首页
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                //销毁加载蒙版
                SVProgressHUD.dismiss()
                //发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVcNoti, object: nil)
            })
            

            }) { (error) -> () in
            print(error)
        }
    }

}
